
// middleware/auth.js
const jwt = require('jsonwebtoken');
const { fail } = require('../utils/response');
// 白名单路由（无需验证）
const WHITE_LIST = [
  '/api/users/login',
  '/api/users/captcha',
  '/api/users/verify-captcha'
];

// 1. Token验证中间件
exports.authMiddleware = (req, res, next) => {
  if (WHITE_LIST.includes(req.path)) {
    return next(); // 放行白名单路由
  }
  const token = req.headers.authorization?.split(' ')[1]; // Bearer <token>

  if (!token) {
    return fail(res, "未提供tokne", 403);
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your_secret_key');
    req.user = decoded;
    next();
  } catch (err) {
    return fail(res, "token过期", 401);
  }
};
